package com.xyh.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @Author:kyle
 * @Date:2020/12/14 - 12:51
 * @Project:spring_demo1
 * @Package:com.xyh.config
 * @Version:1.0
 */
@Configuration
@ComponentScan(basePackages ={"com.xyh"})
@MapperScan(basePackages = {"com.xyh.dao"})
@EnableAspectJAutoProxy(proxyTargetClass=true)
@EnableTransactionManagement
public class ApplicationConfig {

    //数据源
    @Bean
    public DataSource dataSource(DBProperties dbProperties){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(dbProperties.getDriverClassName());
        druidDataSource.setUrl(dbProperties.getUrl());
        druidDataSource.setUsername(dbProperties.getUser());
        druidDataSource.setPassword(dbProperties.getPassword());

        druidDataSource.setInitialSize(3);
        druidDataSource.setMaxActive(10);
        druidDataSource.setMinIdle(3);

        return druidDataSource;
    }

    //sqlSessionFactory
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        //设置mybatis数据源
        sqlSessionFactory.setDataSource(dataSource);
        //设置mybatis-config.xml全局配置文件
        sqlSessionFactory.setConfigLocation(new ClassPathResource("mybatis-configuration.xml"));
        //设置mapper文件位置
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("mapper/*.xml");
        sqlSessionFactory.setMapperLocations(resources);
        //设置包下类型别名
        sqlSessionFactory.setTypeAliasesPackage("com.xyh.po");

        return sqlSessionFactory;
    }

    //事务
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }

}
